using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using Microsoft.Extensions.DependencyInjection;
using NHibernate;
using NHibernate.Dialect;
using NHibernate.Driver;
using NHibernate.Linq;
using NLog.Web;
using Xunit.Abstractions;

namespace Crux.Core.NHibernate.Test;
/// <summary>
/// TestNHibernate
/// </summary>
public class TestNHibernate
{
    protected readonly ITestOutputHelper output;
    protected IServiceProvider? serviceProvider;
    public TestNHibernate(ITestOutputHelper output)
    {
        this.output = output;
        this.InitServiceProvider();
    }
    private void InitServiceProvider()
    {
        IServiceCollection services = new ServiceCollection();
        services.AddMemoryCache();
        services.AddLogging((builder) =>
        {
            builder.AddNLogWeb();
        });

        services.Configure<NHibernateOptions<TestDbContext>>(options =>
        {
            IPersistenceConfigurer? persistenceConfigurer = SQLiteConfiguration.Standard.Dialect<SQLiteDialect>()
            .Driver<SQLite20Driver>().ConnectionString("Data Source=test.db").AdoNetBatchSize(20);

            options.Configuration = Fluently.Configure().Database(persistenceConfigurer)
                .ExposeConfiguration(config =>
                   config.SetProperty("hbm2ddl.auto", "update")
                   .SetProperty("hbm2ddl.keywords", "auto-quote")
                   .SetProperty("show_sql", "true")
                   .SetProperty("format_sql", "true"))
                .BuildConfiguration();
            options.Configuration.LinqQueryProvider<DefaultQueryProvider>();
            options.Configuration.LinqToHqlGeneratorsRegistry<ExtendedLinqtoHqlGeneratorsRegistry>();
            options.Configuration.Proxy(p =>
            {
                p.Validation = true;
            });
            options.Configuration.AddMapping(TestDbContext.BuildMapping());

        });
        services.AddNHibernate();

        this.serviceProvider = services.BuildServiceProvider();

        var factory = serviceProvider.GetRequiredService<Microsoft.Extensions.Logging.ILoggerFactory>();

        NHibernateLogger.SetLoggersFactory(new MicrosoftLoggerFactory(factory));
    }
}